﻿#include "SerialDialog.h"
#include "ui_SerialDialog.h"
#include "services/tlv/Hardware/SerialTlv.h"
#include "services/tlv/Com/TlvThreadCom.h"

#include "components/FWidgets/FMessageBox/FMessageBox.h"
#include <QDebug>

SerialDialog::SerialDialog(QWidget *parent)
    : HWBaseDialog(parent)
    , ui(new Ui::SerialDialog)
{
    ui->setupUi(this);
    setWindowTitle(tr("Serial Port"));

    on_btnRefresh_clicked();
    SerialTlv* stlv = SerialTlv::instance();
    if (stlv->isOpen()) {
        for (auto& port : m_ports) {
            if (port.portName() == stlv->portName()) {
                ui->cbSerialList->setCurrentText(serialPortInfo2String(port));
                break;
            }
        }
        ui->cbBaudrate->setCurrentText(QString::number(stlv->baudRate()));
    }
}

SerialDialog::~SerialDialog()
{
    delete ui;
}

int SerialDialog::exec()
{
    // 虚函数不要在构造函数中调用，所以只能在exec中调用了，外部一定会调用exec方法的！
    if (SerialTlv::instance()->isOpen()) {
        setUIEnabled(false);
    } else {
        setUIEnabled(true);
    }
    return QDialog::exec();
}

QString SerialDialog::serialPortInfo2String(const QSerialPortInfo &port)
{
    return QString("%1  (%2)").arg(port.description(), port.portName());
}

void SerialDialog::setUIEnabled(bool en)
{
    ui->btnRefresh->setEnabled(en);
    ui->cbSerialList->setEnabled(en);
    ui->cbBaudrate->setEnabled(en);
    if (en) ui->btnOpen->setText(tr("Open"));
    else ui->btnOpen->setText(tr("Close"));
}

void SerialDialog::on_btnRefresh_clicked()
{
    ui->cbSerialList->clear();
    m_ports = QSerialPortInfo::availablePorts();
    for (auto& port : m_ports) {
        ui->cbSerialList->addItem(serialPortInfo2String(port));
    }
}


void SerialDialog::on_btnOpen_clicked()
{
    if (m_ports.isEmpty()) {
        FMessageBox::warning(this, tr("Warning"), tr("Serial port not recognized."));
        return;
    }

    int comID = ui->cbSerialList->currentIndex();
    QString com = m_ports[comID].portName();

    SerialTlv* stlv = SerialTlv::instance();
    TlvThreadCom* ttCom = TlvThreadCom::instance();

    if (!changeWorker(stlv)) return;  // 成功切换worker才能打开

    bool ok = false;
    uint32_t baud = ui->cbBaudrate->currentText().toUInt(&ok);
    if (!ok) {
        FMessageBox::critical(this, tr("Error"), tr("Please enter the correct baud rate."));
        return;
    }
    stlv->setAttr(com, baud);
    setUIEnabled(false);
    ttCom->open();
}


void SerialDialog::on_btnCancel_clicked()
{
    reject();
}

